package com.lyfei.yd.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyfei.yd.common.exception.CustomException;
import com.lyfei.yd.common.utils.StringUtils;
import com.lyfei.yd.system.domain.entity.Banner;
import com.lyfei.yd.system.domain.entity.BannerItem;
import com.lyfei.yd.system.domain.entity.Reservation;
import com.lyfei.yd.system.domain.vo.BannerVo;
import com.lyfei.yd.system.mapper.BannerMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service("bannerService")
public class BannerService extends BaseService<BannerMapper, Banner> {
    @Autowired
    private BannerItemService bannerItemService;

    @Override
    public boolean saveOrUpdate(Banner entity) {
        if(StringUtils.isEmpty(entity.getName())) {
            throw  new CustomException("banner名称不能为空");
        }

        Banner existBanner = this.getByName(entity.getName());
        if(existBanner != null && (entity.getId() == null  || !existBanner.getId().equals(entity.getId()))) {
            throw  new CustomException("banner名称已存在");
        }

        // 设置创建时间
        if (entity.getId() == null) {
            entity.setCreateTime(new Date());
        }

        entity.setUpdateTime(new Date());

        if(!super.saveOrUpdate(entity)) {
            throw new RuntimeException("banner记录保存失败");
        }

        return true;
    }

    public IPage<Banner> page(Integer current, Integer size) {
        return this.page(new Page<>(current, size));
    }

    public BannerVo getBannerDetail(Long id) {
        Banner banner = this.getById(id);
        return this.toBannerVo(banner);
    }

    private BannerVo toBannerVo(Banner banner) {
        BannerVo bannerVo = new BannerVo();
        if(banner == null) {
            throw new CustomException("banner记录不存在");
        }

        BeanUtils.copyProperties(banner, bannerVo);

        bannerVo.setBannerItems(bannerItemService.list(new LambdaQueryWrapper<BannerItem>()
                .eq(BannerItem::getBannerId, banner.getId())
                .eq(BannerItem::getDeleted, false)));

        return bannerVo;
    }

    public BannerVo getBannerDetailByName(String name) {
        Banner banner = this.getByName(name);
        if(banner == null) {
            throw new CustomException("banner不存在");
        }

        return this.toBannerVo(banner);
    }

    public Banner getByName(String name) {
        return this.getOne(new LambdaQueryWrapper<Banner>()
                .eq(Banner::getName, name)
                .eq(Banner::getDeleted, false));
    }
}
